/**
 * @ShardedJedisPoolBeanFactory.java  COPYRIGHT xiaojian
 * 
 * Created on 2019年7月29日 下午2:37:05
 */
package xj.toolkit.redis.shard;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.FactoryBean;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;

import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.JedisShardInfo;
import redis.clients.jedis.Protocol;
import redis.clients.jedis.ShardedJedisPool;

/**
 * @author <a href="mailto:cxj2000@gmail.com">xiaojian.cao</a>
 *
 */
public class ShardedJedisPoolBeanFactory implements FactoryBean<ShardedJedis2Pool> {

	private ShardedJedis2Pool pool = null;

	private JedisPoolConfig jedisPoolConfig = null;

	private int connectionTimeout = Protocol.DEFAULT_TIMEOUT;

	/**
	 * 分片的连接字符串。
	 */
	private String shardedRedisConnString = null;

	public String getShardedRedisConnString() {
		return shardedRedisConnString;
	}

	public void setShardedRedisConnString(String shardedConnStr) {
		this.shardedRedisConnString = shardedConnStr;
	}

	public JedisPoolConfig getJedisPoolConfig() {
		return jedisPoolConfig;
	}

	public void setJedisPoolConfig(JedisPoolConfig jedisPoolConfig) {
		this.jedisPoolConfig = jedisPoolConfig;
	}

	public int getConnectionTimeout() {
		return connectionTimeout;
	}

	public void setConnectionTimeout(int connectionTimeout) {
		this.connectionTimeout = connectionTimeout;
	}

	public void init() throws Exception {
		Preconditions.checkArgument(StringUtils.isNoneBlank(shardedRedisConnString));

		String[] preConnStr = StringUtils.split(shardedRedisConnString, "|");

		Preconditions.checkArgument(preConnStr != null && preConnStr.length > 0,
				"Invalid connStr[" + shardedRedisConnString + "].");

		List<JedisShardInfo> infos = Lists.newArrayList();
		for (String str : preConnStr) {
			JedisShardInfo jedisShardInfo = new JedisShardInfo(str);
			jedisShardInfo.setConnectionTimeout(connectionTimeout);
			infos.add(jedisShardInfo);
		}

		pool = new ShardedJedis2Pool(jedisPoolConfig, infos);
	}

	public void destory() {
		if (this.pool != null) {
			pool.destroy();
		}
	}

	@Override
	public ShardedJedis2Pool getObject() throws Exception {
		return pool;
	}

	@Override
	public Class<?> getObjectType() {
		return ShardedJedisPool.class;
	}

	@Override
	public boolean isSingleton() {
		return true;
	}
}
